package com.local.coupon.service.impl;

import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.util.ResultUtil;
import com.local.coupon.mapper.CouponMapper;
import com.local.coupon.mapper.UserCouponRecordMapper;
import com.local.coupon.pojo.Coupon;
import com.local.coupon.pojo.UserCouponRecord;
import com.local.coupon.service.CouponService;
import com.local.coupon.service.UserCouponRecordService;
import com.local.goods.feign.GoodsServiceFeign;
import com.local.goods.pojo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserCouponRecordServiceImpl implements UserCouponRecordService {

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;

    @Autowired
    private UserCouponRecordMapper userCouponRecordMapper;

    @Autowired
    private CouponMapper couponMapper;

    /**
     * 得到用户的可以正常使用的优惠券，用于订单支付
     * @param userId
     * @return
     */
    @Override
    public List<UserCouponRecord> getByUserIdForPay(Integer userId, Integer priceTotal, List<Integer> goodsIdList) {
        //查询用户目前可用的优惠券记录
        List<UserCouponRecord> userCouponRecordList = userCouponRecordMapper.getByUserId(userId);
        if (Objects.isNull(userCouponRecordList) || userCouponRecordList.size() == 0) {
            return userCouponRecordList;
        }

        //查询用户目前可用的优惠券记录的详细信息
        List<Integer> couponIdList = userCouponRecordList.stream().map(UserCouponRecord::getCouponId).collect(Collectors.toList());
        List<Coupon> couponList = couponMapper.getByIds(couponIdList);
        for (UserCouponRecord userCouponRecord : userCouponRecordList) {
            for (Coupon coupon : couponList) {
                if (userCouponRecord.getCouponId().equals(coupon.getCouponId())) {
                    userCouponRecord.setName(coupon.getCouponName());
                    userCouponRecord.setCouponDesc(coupon.getCouponDesc());
                    userCouponRecord.setDiscount(coupon.getDiscount());
                    userCouponRecord.setMin(coupon.getMin());
                    userCouponRecord.setGoodsType(coupon.getGoodsType());
                    userCouponRecord.setGoodsValue(coupon.getGoodsValue());
                    userCouponRecord.setStartTime(coupon.getCouponStartTime());
                    userCouponRecord.setEndTime(coupon.getCouponEndTime());
                }
            }
        }


        String dateTimeNow = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return userCouponRecordList.stream().filter(item -> {
            String startTime = item.getStartTime();
            String endTime = item.getEndTime();
            //判断优惠券的使用时间是否有效
            if (Objects.isNull(startTime) || Objects.isNull(endTime) ||  startTime.compareTo(dateTimeNow) > 0 || endTime.compareTo(dateTimeNow) < 0) {
                return false;
            }

            boolean useStatus = false;
            if (item.getMin() <= priceTotal) {
                if (item.getGoodsType() == 1) { //指定分类可用
                    String[] split = item.getGoodsValue().split(",");
                    List<Integer> categoryIdList = Arrays.stream(split).map(Integer::valueOf).collect(Collectors.toList());

                    ResultUtil<List<Goods>> goodsListResult = goodsServiceFeign.getGoodsListByIds(goodsIdList);
                    if (goodsListResult.getCode() != 200) {
                        throw new BusinessException(goodsListResult.getCode(), goodsListResult.getMessage());
                    }
                    List<Goods> goodsList = goodsListResult.getData();
                    List<Integer> goodsCategoryList = goodsList.stream().map(Goods::getGoodsCategoryId).collect(Collectors.toList());
                    for (Integer goodsCategoryId : goodsCategoryList) {
                        if (categoryIdList.contains(goodsCategoryId)) {
                            useStatus = true;
                            break;
                        }
                    }
                } else if (item.getGoodsType() == 2) { //指定商品可用
                    String[] split = item.getGoodsValue().split(",");
                    List<Integer> couponGoodsIdList = Arrays.stream(split).map(Integer::valueOf).collect(Collectors.toList());
                    for (Integer cartGoodsId : goodsIdList) {
                        if (couponGoodsIdList.contains(cartGoodsId)) {
                            useStatus = true;
                            break;
                        }
                    }
                } else { //全场通用
                    useStatus = true;
                }
            }

            return useStatus;
        }).sorted(Comparator.comparingInt(UserCouponRecord::getDiscount)).collect(Collectors.toList());
    }


    /**
     * 通过id查询数据
     * @param userCouponRecordId
     * @return
     */
    @Override
    public UserCouponRecord getById(Integer userCouponRecordId) {
        return userCouponRecordMapper.getById(userCouponRecordId);
    }


    /**
     * 优惠券使用后，更新使用状态
     * @param userCouponRecord
     * @return
     */
    @Override
    public Integer updateUseOrderId(UserCouponRecord userCouponRecord) {
        return userCouponRecordMapper.updateUseOrderId(userCouponRecord);
    }
}
